<template>
    <div class="p-6 flex flex-col ">

        <!-- 应用状态控制区 -->
        <div class="mb-8 bg-white rounded-xl shadow-sm p-8 border border-gray-100 transition-all hover:shadow-md">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-xl font-semibold text-gray-900">应用状态</h2>
                    <p class="text-sm text-gray-500 mt-1.5">启用后应用将在所有平台生效</p>
                </div>
                <label class="relative inline-flex items-center cursor-pointer group">
                    <input type="checkbox" class="sr-only peer" v-model="appData.enable" @change="handleToggleEnable">
                    <div
                        class="w-14 h-8 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-100 rounded-full peer peer-checked:after:translate-x-6 peer-checked:after:border-white after:content-[''] after:absolute after:top-1 after:left-1 after:bg-white after:border-gray-300 after:border after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-green-600"></div>
                    <span class="ml-3 text-sm font-medium"
                          :class="appData.enable ? 'text-green-600' : 'text-gray-500'">{{ appData.enable ? '已启用' : '已禁用' }}</span>
                </label>
            </div>
            <div v-if="theme=='small'" class="mt-6 pt-6 border-t border-gray-100">
                <button
                    class="px-5 py-2.5 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-lg hover:shadow-lg transition-all text-sm !rounded-button whitespace-nowrap"
                    @click="syncConfigToApp"
                >
                    <i class="fas fa-rocket mr-2"></i>
                    发布最新设计
                </button>
                <p class="text-xs text-gray-500 mt-3 opacity-80">编排节点发生变更需发布最新设计后生效</p>
            </div>
        </div>
        <!-- 平台选择区 -->
        <div class="mb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">选择发布平台</h2>
            <div class="grid grid-cols-5 gap-6">
                <div
                    v-for="platform in platforms"
                    :key="platform.id"
                    class="relative"
                >
                    <label class="block cursor-pointer">
                        <input
                            type="checkbox"
                            v-model="selectedPlatforms"
                            :value="platform.id"
                            class="hidden"
                        >
                        <div
                            class="h-32 rounded-xl border-2 flex flex-col items-center justify-center transition-all duration-300 group transform hover:scale-[1.02]"
                            :class="{'border-blue-500 bg-white shadow-md': selectedPlatforms.includes(platform.id),'border-gray-100 hover:border-blue-200 bg-white hover:shadow-md': !selectedPlatforms.includes(platform.id)}"
                        >
                            <div class="relative">
                                <div
                                    class="w-12 h-12 rounded-full flex items-center justify-center mb-3 transition-all duration-300 group-hover:bg-blue-50"
                                    :class="{'bg-blue-50': selectedPlatforms.includes(platform.id),'bg-gray-50': !selectedPlatforms.includes(platform.id)}"
                                >
                                    <jb-icon :local="true" :icon="platform.icon"
                                             class="text-xl"
                                             :color="selectedPlatforms.includes(platform.id) ? platform.color : '#9CA3AF'"
                                    ></jb-icon>
                                </div>
                                <div
                                    class="absolute -top-1 -right-1 w-5 h-5 rounded-full border-2 border-white flex items-center justify-center transition-all"
                                    :class="{'bg-blue-500': selectedPlatforms.includes(platform.id),'bg-gray-200': !selectedPlatforms.includes(platform.id)}"
                                >
                                    <i
                                        class="fas fa-check text-xs text-white"
                                        v-show="selectedPlatforms.includes(platform.id)"
                                    ></i>
                                </div>
                            </div>
                            <span
                                class="text-sm font-medium transition-colors duration-300 group-hover:text-blue-500"
                                :class="{'text-blue-600': selectedPlatforms.includes(platform.id),'text-gray-700': !selectedPlatforms.includes(platform.id)}"
                            >{{ platform.name }}</span>
                        </div>
                    </label>
                </div>
            </div>
        </div>
        <!-- 平台设置区 -->
        <div class="pb-6 flex-1 ">
            <div class=" flex gap-2">
                <!-- 网页端设置 -->
                <div
                    v-if="selectedPlatforms.includes('WEB')"
                    class="w-96 flex-shrink-0 bg-white rounded-xl shadow-lg p-6 border border-gray-100 transition-all duration-300 hover:shadow-xl hover:border-blue-100"
                >
                    <h3 class="text-xl font-semibold text-gray-900 mb-6 flex items-center">
                        <div class="w-10 h-10 rounded-lg bg-blue-50 flex items-center justify-center mr-3">
                            <jb-icon :local="true" icon="iconfont:web"
                                     class="text-xl text-blue-500"
                            ></jb-icon>
                        </div>
                        <span>网页端设置</span>
                    </h3>
                    <div class="space-y-6">
                        <div>
                            <div class="flex items-center justify-between mb-3">
                                <h4 class="text-sm font-medium text-gray-600 uppercase tracking-wider">发布方式</h4>
                                <div class="flex space-x-2">
                                    <button
                                        @click="copyUrl(appUrl)"
                                        class="w-8 h-8 flex items-center justify-center bg-white border border-gray-200 hover:bg-blue-50 hover:border-blue-100 rounded-lg transition-all duration-200 group"
                                        title="复制链接"
                                    >
                                        <i class="far fa-copy text-gray-500 group-hover:text-blue-500 transition-colors"></i>
                                    </button>

                                    <n-popover placement="bottom" trigger="hover" style="width: 300px;height: 300px;">
                                        <template #trigger>
                                            <button
                                                class="w-8 h-8 flex items-center justify-center bg-white border border-gray-200 hover:bg-blue-50 hover:border-blue-100 rounded-lg transition-all duration-200 group"
                                            >
                                                <i class="fa-solid fa-qrcode"></i>
                                            </button>
                                        </template>
                                        <span
                                            style="display: flex ;flex-flow: column; justify-content: flex-start;align-items: center;margin-top: 20px">
                                                     <n-space vertical style="align-items: center; padding: 0px !important;">
                                                        <n-qr-code id="qr-code" :value="url" :size="200"/>
                                                     </n-space>

                                                    <div class="flex justify-center space-x-2 mt-3">
                                                            <button @click.stop="handleDownloadQRCode"
                                                                    class="px-3 py-1.5 bg-white border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-xs whitespace-nowrap">
                                                                    <i class="fas fa-download mr-1"></i>下载</button>
                                                            <button @click.stop="openNewPage"
                                                                    class="px-3 py-1.5 bg-blue-50 border border-blue-100 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-xs whitespace-nowrap">
                                                                    <i class="fas fa-external-link-alt mr-1"></i>打开
                                                            </button>
                                                    </div>
                                            </span>
                                    </n-popover>
                                </div>
                            </div>
                            <div class="space-y-3">
                                <label class="flex items-start p-3 rounded-lg transition-all duration-200 hover:bg-gray-50 cursor-pointer"
                                       :class="{ 'bg-blue-50 border border-blue-100': webPublishData.accessType === 1 }">
                                    <input
                                        type="radio"
                                        name="access_type"
                                        value="public"
                                        v-model="selectedPublishMethod"
                                        class="mt-1 mr-3"
                                    >
                                    <div class="flex-1">
                                        <div class="font-medium text-gray-800">公开发布</div>
                                        <div class="text-xs text-gray-500 mt-1">所有用户可访问</div>
                                    </div>
                                </label>
                                <label class="flex items-start p-3 rounded-lg transition-all duration-200 hover:bg-gray-50 cursor-pointer"
                                       :class="{ 'bg-blue-50 border border-blue-100': webPublishData.accessType === 3 }">
                                    <input
                                        type="radio"
                                        name="access_type"
                                        value="password"
                                        v-model="selectedPublishMethod"
                                        class="mt-1 mr-3"
                                    >
                                    <div class="flex-1">
                                        <div class="flex items-center justify-between">
                                            <div>
                                                <div class="font-medium text-gray-800">密码发布</div>
                                                <div class="text-xs text-gray-500 mt-1">输入密码后访问</div>
                                            </div>
                                            <button
                                                v-if="webPublishData.accessType === 3"
                                                @click.stop="openPwdSetDialog()"
                                                class="px-3 py-1 text-sm bg-green-100 text-green-600 rounded-md hover:bg-green-200 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-opacity-50"
                                            >
                                                设置密码
                                            </button>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- API调用设置 -->
                <div
                    v-if="selectedPlatforms.includes('API')"
                    class="w-96 flex-shrink-0 bg-white rounded-xl shadow-sm p-6 border border-gray-100 transition-all duration-300 hover:shadow-md hover:border-green-100"
                >
                    <div class="flex items-center mb-6">
                        <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-green-100 to-green-50 flex items-center justify-center mr-4">
                            <jb-icon :local="true" icon="iconfont:api"
                                     class="text-xl text-green-500"
                            ></jb-icon>
                        </div>
                        <h3 class="text-lg font-semibold text-gray-900">API调用设置</h3>
                    </div>
                    <div class="space-y-5">
                        <div class="relative">
                            <label class="absolute -top-2 left-3 px-1 bg-white text-xs font-medium text-gray-500">API调用地址</label>
                            <input
                                type="text"
                                v-model="apiUrl"
                                readonly
                                class="w-full px-4 py-3 border
                                    border-gray-200 rounded-lg text-sm
                                     transition-all duration-200 bg-gray-100 text-gray-400"
                                style="outline: none;"
                            >

                            <!-- 添加的复制按钮 -->
                            <button
                                @click="copyUrl(apiUrl)"
                                title="复制链接"
                                class="absolute right-3 top-1/2 transform -translate-y-1/2 px-3 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-xs whitespace-nowrap"
                            >
                                <i class="far fa-copy text-gray-500 group-hover:text-blue-500 transition-colors"></i>

                            </button>
                        </div>
                    </div>
                    <!-- 新增API请求示例区域 -->
                    <div class="mt-5">
                        <h4 class="text-sm font-medium text-gray-600 mb-2">
                            请求示例
                            <span class="inline-block px-2 py-0.5 bg-blue-100 text-blue-600 text-xs rounded ml-2">POST</span>
                        </h4>
                        <div class="bg-gray-50 rounded-lg p-3 border border-gray-200">
                            <pre class="text-xs text-gray-700 overflow-x-auto" style="max-height: 120px;">{{ formattedRequestExample }}</pre>
                        </div>
                    </div>

                    <!-- 新增API响应示例区域 -->
                    <div class="mt-3">
                        <h4 class="text-sm font-medium text-gray-600 mb-2">响应示例</h4>
                        <div class="bg-gray-50 rounded-lg p-3 border border-gray-200">
                            <pre class="text-xs text-gray-700 overflow-x-auto" style="max-height: 150px;">{{ formattedResponseExample }}</pre>
                        </div>
                    </div>


                </div>


            </div>
        </div>
    </div>

    <!-- 密码设置弹窗 -->
    <div v-if="showPasswordSettingModal"
         :class="`${theme}-publish-container`"
         class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50" style="margin:0">
        <div class="bg-white rounded-lg shadow-lg p-6 w-96">
            <h3 class="text-lg font-medium text-gray-900 mb-4">设置访问密码</h3>
            <div class="mb-4">
                <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                    密码
                    <span class="text-red-500 ml-0.5">*</span>
                </label>
                <n-input
                    v-model:value="accessPwd"
                    type="password"
                    id="password"
                    show-password-on="click"
                    :status="!!passwordError?'error':undefined"
                    placeholder="请输入访问密码"
                    required
                />
                <p v-if="passwordError" class="mt-1 text-xs text-red-500">{{ passwordError }}</p>
            </div>
            <div class="flex justify-end space-x-3">
                <button
                    @click="closePasswordModal"
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-opacity-50"
                >
                    取消
                </button>
                <button
                    @click="setAccessPassword"
                    class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-50"
                >
                    确定
                </button>
            </div>
        </div>
    </div>

</template>
<script setup>
import {ref, computed, onMounted, nextTick, watch} from 'vue';
import {useMessage} from 'naive-ui';
import {JBoltApi} from "@/service/request/index.js";
import {copy} from "@/utils/common/others.js";
import {getServiceEnvConfig} from "~/.env-config.js";

const {url} = getServiceEnvConfig(import.meta.env)

const props = defineProps({
    appId: {
        type: String,
        required: true
    },
    theme: {
        type: String,
        required: true
    },
});
const flag = ref(false);//控制是否是第一次访问
const message = useMessage();
const appUrl = ref('');
const apiUrl = ref('');

// API示例数据
const requestExample = ref({
    sessionId: "会话ID",
    msg: "消息内容"
});

const responseExample = ref({
    code: 0,
    data: [
        {
            renderType: "markdown",
            content: "回答的内容"
        }
    ],
    state: "ok",
    msg: null
});

// 格式化JSON的计算属性
const formattedRequestExample = computed(() => {
    return JSON.stringify(requestExample.value, null, 2);
});

const formattedResponseExample = computed(() => {
    return JSON.stringify(responseExample.value, null, 2);
});



// 平台相关设置
const platforms = [
    {id: 'WEB', name: '网页端', icon: 'iconfont:web', color: 'rgba(9,129,255,0.94)'},
    {id: 'API', name: 'API调用', icon: 'iconfont:api', color: '#10B981'},
];
const selectedPlatforms = ref([]);

// 监听selectedPlatforms
watch(selectedPlatforms, (newValue, oldValue) => {

    if (flag.value == false) return;


    // 找出变化的平台（只会有一个）
    const addedPlatform = newValue.find(item => !oldValue.includes(item));
    const removedPlatform = oldValue.find(item => !newValue.includes(item));
    const changedPlatform = addedPlatform || removedPlatform;

    // 如果没有变化，直接返回
    if (!changedPlatform) return;

    // 映射平台到类型和对应的数据对象
    const platformMap = {
        'WEB': {
            type: 1,
            dataRef: webPublishData
        },
        'API': {
            type: 2,
            dataRef: apiPublishData
        }
        // 可以轻松扩展更多平台
    };

    // 获取平台对应的配置
    const platformConfig = platformMap[changedPlatform];


    if (!platformConfig) return;

    // 更新启用状态
    const isEnabled = !!addedPlatform; // 如果是添加平台则启用，否则禁用
    platformConfig.dataRef.value.enable = isEnabled;

    // 保存设置
    saveSettings(platformConfig.type, true);
}, {deep: true});

// 访问方式设置
const selectedPublishMethod = ref('');

// 应用数据
const appData = ref({
    id: '',
    enable: false,
    sn: '',
    name: ''
});
//web的应用数据
const webPublishData = ref({
    accessType: 1,
    accessPwd: '',
    enable: false,
})
//API调用的应用数据
const apiPublishData = ref({
    enable: false,
    corpId: "",
    //应用id
    agentId: '',
    //应用secret
    corpSecret: '',
    //token
    token: '',
    aesKey: '',
})

// web网页页面的计算当前选择的发布方式
const actualPublishMethod = computed(() => {
    switch (webPublishData.value.accessType) {
        case 1:
            return 'public';
        case 3:
            return 'password';
    }
    return null;
});

// 用户分组相关
const userGroupTags = ref([]);
const choosedTags = ref([]);
const userGroupTagsCount = computed(() => {
    return Array.isArray(userGroupTags.value) ? userGroupTags.value.length : 0;
});

// 监听web的发布方式变化
watch(() => selectedPublishMethod.value, (methodId, oldValue) => {
    console.debug("更新访问方式", methodId);
    if (methodId === 'password' && oldValue) {
        showPasswordSettingModal.value = true;
    } else if (methodId === 'group' && oldValue) {
        showGroupSelectionModal.value = true;
    } else {
        if (oldValue) {
            webPublishData.value.accessType = methodId == 'public' ? 1 : (methodId == 'login' ? 2 : 1);
            saveSettings(1);
        }
    }
});

// 弹窗相关
const showPasswordSettingModal = ref(false);
const passwordError = ref('');
const accessPwd = ref('');
const showGroupSelectionModal = ref(false);
const groupSelectionError = ref('');
const showQRCode = ref(false);

// 平台设置
const dingtalkSettings = ref({
    agentId: '',
    appKey: '',
    appSecret: ''
});
const feishuSettings = ref({
    appId: '',
    appSecret: '',
    encryptKey: ''
});
const officialAccountSettings = ref({
    appId: '',
    appSecret: '',
    token: '',
    encodingAESKey: ''
});

// 保存平台设置
const saveSettings = (platform, enableSetting) => {

    let config = {};
    if (platform == 1) { //web访问方式
        config = {...webPublishData.value};
    } else if (platform == 2) {//API调用
        if (!enableSetting) {
            if (apiPublishData.value.corpId.trim() === '' ||
                apiPublishData.value.agentId.trim() === '' ||
                apiPublishData.value.corpSecret.trim() === '' ||
                apiPublishData.value.token.trim() === '' ||
                apiPublishData.value.aesKey.trim() === ''
            ) {
                return;
            }
        }
        config = apiPublishData.value;
    }

    JBoltApi.tryPost('/aiAppConfig/updateAccessConfig', {
        appId: appData.value.id,
        appPublishType: platform,
        jsonConfig: JSON.stringify(config)
    }).then(res => {
        message.success(`${appData.value.name}--${platform == 1 ? '网页访问' : 'API调用'} 设置已更新`);
    });

};

// 密码设置相关函数
function openPwdSetDialog() {
    passwordError.value = '';
    accessPwd.value = webPublishData.value.accessPwd;
    showPasswordSettingModal.value = true;
}

function setAccessPassword() {
    passwordError.value = '';
    if (accessPwd.value?.trim()) {
        showPasswordSettingModal.value = false;
        if (selectedPublishMethod.value == 'password') {
            webPublishData.value.accessType = 3;
        }
        webPublishData.value.accessPwd = accessPwd.value;
        saveSettings(1);
    } else {
        passwordError.value = '密码不能为空';
    }
}

function closePasswordModal() {
    showPasswordSettingModal.value = false;
    selectedPublishMethod.value = actualPublishMethod.value;
}


// URL和二维码相关函数
function copyUrl(url) {
    if (!url) return;
    copy(url);

}

function handleDownloadQRCode() {
    const canvas = document.querySelector('#qr-code canvas');
    if (canvas) {
        const url = canvas.toDataURL('image/png');
        const a = document.createElement('a');
        a.download = appData.value.name + Date.now() + '.png';
        a.href = url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        message.success("二维码下载成功");
    } else {
        message.error("二维码下载失败");
    }
}

function openNewPage() {
    if (appUrl.value) {
        window.open(appUrl.value);
    } else {
        message.error("未发布无访问地址");
    }
}

// 切换发布状态
async function handleToggleEnable() {
    const {result} = await JBoltApi.get(`/aiApp/toggleEnable/${props.appId}`);
    if (result) {
        message.success("发布状态已更新");
        loadData();
    }
}


function syncConfigToApp() {
    JBoltApi.tryGet(`/aiAppDesign/publish/${props.appId}`).then(
        res => {
            if (res) {
                message.success("发布成功");
            }
        }
    ).catch((err) => {
        console.error(err);
    });
}

function loadData() {
    JBoltApi.tryGet(`/aiAppConfig/getAccessConfigByAppId/${props.appId}`).then(res => {
        //先获取app的值
        appData.value = {...res.data.app};
        appUrl.value = `${window.location.origin}/aiApp/${appData.value.sn}`;
        apiUrl.value = `${url}/aiApp/${appData.value.sn}`;
        //web的值
        if (res.data.webConfig) {
            webPublishData.value = {...res.data.webConfig}
            //判断enable是true,就往selectedPlatforms添加
            if (res.data.webConfig.enable) {
                selectedPlatforms.value.push('WEB');
            }
            selectedPublishMethod.value = actualPublishMethod.value;

        }
        //API调用的值
        if (res.data.apiConfig) {
            apiPublishData.value = {...res.data.apiConfig};
            if (res.data.apiConfig.enable) {
                selectedPlatforms.value.push('API');
            }
        }
        flag.value = true;
    });

}

onMounted(() => {
    if (props.appId) {
        loadData();
    }
    console.debug("发布方式", props.theme)
});
</script>
<style scoped>
/* 自定义滚动条样式 */
::-webkit-scrollbar {
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 弹窗动画 */
.modal-enter-active,
.modal-leave-active {
    transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
    opacity: 0;
}

.modal-content-enter-active,
.modal-content-leave-active {
    transition: all 0.3s ease;
}

.modal-content-enter-from,
.modal-content-leave-to {
    transform: translateY(20px);
    opacity: 0;
}

.chain-publish-container {
    height: 560px;
    border-radius: 10px;

}

#qr-code {
    padding: 0px !important;
}
</style>
